package marvin.webapp.audio.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConfigReader {
	public static final String ROOT_FILES_KEY = "ROOT_FILES_KEY";
	public static final String WEB_RADIOS_KEY = "WEB_RADIOS_KEY";

	private static String configFilePath = System.getenv("MARVIN_CONFIG");

	private static Map<String, List<String>> configMap;
	
	public static List<String> getParameters(String key){
		if(configMap == null){
			readConfiguration();
		}
		
		List<String> result = new ArrayList<String>();
		
		if(configMap.containsKey(key))
			result = configMap.get(key);
		
		return result;
	}
	
	
	public static void readConfiguration(){
		System.out.println("Try to read $MARVIN_CONFIG/marvin.conf file ("+configFilePath+")");
		File conf = new File(configFilePath+"/marvin.conf");
		
		int rootFileIndex = 0, radioIndex = 0, current = 0;
		
		List<String> rootFiles = new ArrayList<String>();
		List<String> webRadios = new ArrayList<String>();
		
		if(conf.exists()){	
			try{
				InputStream ips=new FileInputStream(conf); 
				InputStreamReader ipsr=new InputStreamReader(ips);
				BufferedReader br=new BufferedReader(ipsr);
				String ligne;
				while ((ligne=br.readLine())!=null){
					current++;
					System.out.println(ligne);
					if(!ligne.startsWith("#") && ! ligne.isEmpty()){
						if(ligne.startsWith("Root files:")){
							rootFileIndex = current;
						} else if(ligne.startsWith("Web radio URLs:")){
							radioIndex = current;
						} else {
							if(current > rootFileIndex && radioIndex == 0)
								rootFiles.add(ligne);
							else if (current > radioIndex)
								webRadios.add(ligne);
						}
					}
				}
				br.close(); 
			}catch (Exception e){
				System.out.println(e.toString());
			}			
		}
		configMap = new HashMap<String, List<String>>();
		configMap.put(ROOT_FILES_KEY, rootFiles);
		configMap.put(WEB_RADIOS_KEY, webRadios);
	}
}
